import { Injectable } from '@angular/core';
import * as WebIM from '../../../src/webimSDK3.0.6.js'
import * as config from '../../../src/WebIMConfig.js'
import { retry } from 'rxjs/operators';
import { Storage } from './Storage.js';
import { AppConfig } from './AppConfig.js';
@Injectable({
    providedIn: 'root'
})
export class MessageUtlis {
    // static conn: any = null;
    public static conn: any = null;
    static getConn() {
        if (!this.conn) {
            this.initWebIM();
        }
        return this.conn;
    }
    static initWebIM() {
        WebIM.config = config.config;
        this.conn = WebIM.conn = new WebIM.default.connection({
            appKey: WebIM.config.appkey,
            isHttpDNS: WebIM.config.isHttpDNS,
            isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
            https: WebIM.config.https,
            url: WebIM.config.xmppURL,
            apiUrl: WebIM.config.apiURL,
            isAutoLogin: WebIM.config.isAutoLogin,
            heartBeatWait: WebIM.config.heartBeatWait,
            autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
            autoReconnectInterval: WebIM.config.autoReconnectInterval,
            isStropheLog: WebIM.config.isStropheLog,
            delivery: WebIM.config.delivery
        })
        console.log('值==', this.conn);
    }
    static listen(conn, callBack) {
        conn.listen({
            onOpened: function (message) {          //连接成功回调
                console.log('连接成功回调', message);
                // AppConfig.IS_SHOW_MSG=false;
                callBack(true);
                // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
                // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
                // 则无需调用conn.setPresence();             
            },
            onClosed: function (message) {
                // AppConfig.IS_SHOW_MSG=true;
                callBack(false);
                console.log('连接关闭回调1', message);
            },
            //连接关闭回调
            onTextMessage: function (message) {
                console.log('收到文本消息', message);
                let list = [];
                list=  Storage.localStorage.get('listChat');
               
                list.push(message)
                Storage.localStorage.set('listChat', list);
                // AppConfig.listChat=list; 
                Storage.sessionStorage.set('isNewMsg','1');
                callBack(message, 'text');
            },   
            onEmojiMessage: function (message) {
                console.log('收到表情消息', message);

            },   
            onPictureMessage: function (message) {
                console.log('收到图片消息', message);
                let list = [];
               
                message.typeMsg='img';

              
                list=  Storage.localStorage.get('listChat');
               
             


                list.push(message)
                // AppConfig.listChat=list;
                Storage.sessionStorage.set('isNewMsg','1');
                Storage.localStorage.set('listChat', list);
                callBack(message, 'img');

            }, //收到图片消息
            onCmdMessage: function (message) {
                console.log('收到命令消息', message);
            },     //收到命令消息
            onAudioMessage: function (message) {
                console.log('收到命收到音频消息令消息', message);
            },   //收到音频消息
            onLocationMessage: function (message) {
                console.log('收到音频消息', message);
            },//收到位置消息
            onFileMessage: function (message) {
                console.log('收到位置消息', message);
            },    //收到文件消息

            onPresence: function (message) { },       //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
            onRoster: function (message) { },         //处理好友申请
            onInviteMessage: function (message) { },  //处理群组邀请
            onOnline: function () { },                  //本机网络连接成功
            onOffline: function () { },                 //本机网络掉线
            onError: function (message) { },          //失败回调
            onBlacklistUpdate: function (list) {       //黑名单变动
                // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
                console.log(list);
            },
            onReceivedMessage: function (message) {
               // console.log('收到消息发送服务器', message);
            },    //收到消息送达服务器回执
            onDeliveredMessage: function (message) {
                console.log('收到消息');

            },   //收到消息送达客户端回执
            onReadMessage: function (message) {
                console.log('收到消息已读回执');
            },        //收到消息已读回执
            onCreateGroup: function (message) { },        //创建群组成功回执（需调用createGroupNew）
            onMutedMessage: function (message) { }        //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
        });
    }

    static sendMSG(senMsg, info, list, callBack) {
        var id = this.conn.getUniqueId();                 // 生成本地消息id
        // console.log("info.from",info.from)
        // return 
        var msg = new WebIM.default.message('txt', id);      // 创建文本消息
        list.push(info)
        // AppConfig.listChat=list;
        Storage.localStorage.set('listChat', list);
        msg.set({
            msg: senMsg,                  // 消息内容
            to: info.from,                          // 接收消息对象（用户id）
            roomType: false,
            ext: {
                nickName:info.nickName,
                to: info.from,     
                // info:list,
            },   
            success: function (id, serverMsgId) {
                console.log("发送返回来的id",id)
                callBack(serverMsgId);
                // console.log('send private text Success',id,serverMsgId);
            },                                       // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
            fail: function (e) {
                console.log("Send private text error");
            }                                        // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
        });
        this.conn.send(msg.body);
    }



    static sendImgMSG(file, item, list, callBack) {
        let reader = new FileReader();
        reader.readAsDataURL(file.data);//异步读取文件内容，结果用data:url的字符串形式表示
       
        var id = this.conn.getUniqueId();                 // 生成本地消息id

       
        var msg = new WebIM.default.message('img', id);      // 创建文本消息
        var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: item.from,  
            ext: {
                nickName:item.nickName,
                to: item.from,     
                // info:list,
            },                        // 接收消息对象
            roomType: false,
            onFileUploadError: function () {
                // callBack();   // 消息上传失败
                console.log('onFileUploadError');
            },
            onFileUploadComplete: function (data) {   // 消息上传成功
                if(data.uri&&data.entities){
                    item.url = data.uri+'/'+data.entities[0].uuid;
                    list.push(item)
                    // AppConfig.listChat=list;
                    Storage.localStorage.set('listChat', list);
                    callBack(data.uri+'/'+data.entities[0].uuid);
                }
                console.log('onFileUploadComplete');
            },
            success: function (id, serverMsgId) {                // 消息发送成功
                // callBack();
                console.log('Success',id);
                console.log('serverMsgId',serverMsgId);
            },
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);
        this.conn.send(msg.body);
    }
}